package com.detect.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArrayList;
import com.detect.core.FileOperator;
import com.detect.core.IFileOperator;
import com.detect.model.FileInfo;

public class ScanService implements IScanService {

	private int cores;
	private List<FileInfo> fileList;
	private List<String> subDirList;
	private boolean isScanSub;
	private String topDir;
	private HashMap<String, List<FileInfo>> duplicateFileList;
	private long minSize;
	private long maxSize;
	private IFileOperator fileOperator;
	
	public ScanService(String topDir, boolean isScanSub, long minSize, long maxSize) {
		cores = getCores();
		fileList = new CopyOnWriteArrayList<FileInfo>();
		//fileList = new ArrayList<FileInfo>();
		this.isScanSub = isScanSub;
		this.topDir = topDir;
		this.maxSize = maxSize;
		this.minSize = minSize;
	}

	private int getCores() {
		return Runtime.getRuntime().availableProcessors() * 2 + 2;
	}
	
	@Override
	public List<FileInfo> getFileInfos() {
		return fileList;
	}

	private void setHashCode() {
		fileOperator.setMD5String(fileList);
		duplicateFileList = fileOperator.getResult();
		if(!duplicateFileList.isEmpty()) {
			Set<String> keys = duplicateFileList.keySet();
			Iterator<String> iterator = keys.iterator();
			while(iterator.hasNext()) {
				String key = iterator.next();
				List<FileInfo> tList = duplicateFileList.get(key);
				if(tList.size() != 1) {
					for(FileInfo fileInfo : tList) {
						System.out.println("Name=" + fileInfo.getFileName() + ", Path=" + fileInfo.getFilePath());
					}
					System.out.println();
				}
			}
		}
	}

	@Override
	public FileInfo getByPath(String path) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public FileInfo getByMD5(String md5) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void doScan() {
		fileOperator = new FileOperator(minSize, maxSize);
		subDirList = fileOperator.scannFiles(fileList, topDir, isScanSub);
		if(!subDirList.isEmpty()) {
			for(String tempPath : subDirList) {
				fileOperator.scannFiles(fileList, tempPath, false);
			}
		}
		
		if(!fileList.isEmpty()) 
			setHashCode();
	}

	@Override
	public int getFileCount() {
		// TODO Auto-generated method stub
		return fileList.size();
	}
}
